<template>
  <el-dialog
          model-value="dialogVisible"
          :title="dialogTitle"
          width="35%"
          align-center
          @close="handleClose"
  >
    <el-button type="success" @click="innerVisible=true" :style="{marginBottom:'15px',display:displayBtn}">选择资产</el-button>
    <el-form ref="formRef" :model="form" :rules="rules" :disabled="formDisabled">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="资产名称：" prop="zcmc">
            <el-input v-model="form.zcmc" placeholder="请选择资产" readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="资产编号：" prop="zcbh">
            <el-input v-model="form.zcbh" placeholder="请选择资产" readonly/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="损坏数量：" prop="shsl">
        <el-input-number v-model="form.shsl" :min="0"/>
      </el-form-item>
      <el-form-item label="故障原因：" prop="gzyy">
        <el-input type="textarea" v-model="form.gzyy" style="font-size: 16px" :autosize="{minRows:5}"/>
      </el-form-item>
      <el-form-item label="送修日期：" prop="sxrq">
        <el-date-picker
                v-model="form.sxrq"
                type="date"
                placeholder="请选择送修日期"
        />
      </el-form-item>
      <el-form-item label="是否损坏：" prop="isScrapped">
        <el-select v-model="form.isScrapped" placeholder="是否损坏" style="width: 100px">
          <el-option
                  v-for="o in 2"
                  :key="o"
                  :label="o!==1?'已损坏':'未损坏'"
                  :value="o"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="维修状况：" prop="wxzk">
        <el-input type="textarea" v-model="form.wxzk" style="font-size: 17px" :autosize="{minRows:5}"/>
      </el-form-item>
      <el-form-item label="维修费用：" prop="wxfy">
        <el-input v-model="form.wxfy"/>
      </el-form-item>
    </el-form>

    <AssetsDialog
            v-model="innerVisible"
            :dialogVisible="innerVisible"
            @id="getAssetById"
    />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/util/request";
import AssetsDialog from "@/views/page/components/assetsDialog";

const formRef = ref(null)

const formDisabled = ref(true);

const displayBtn = ref('block')

/**
 *初始化表单数据
 */
const form = ref({
  id: -1,
  assetid: -1,
  zcmc: "",
  zcbh: "",
  shsl: 0,
  gzyy: "",
  sxrq: "",
  isScrapped: "",
  wxzk: "",
  wxfy: "",
})

const kcsl = ref(-1);

/**
 * 自定义检验规则
 * @param rule
 * @param value
 * @param callback
 */
const shslValidator = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入损坏数量"));
  } else if (value > kcsl.value) {
    callback(new Error("损坏数量不能超过资产实际数量"));
  } else {
    callback();
  }
}

/**
 * 表单校验规则
 */
const rules = ref({
  zcmc: [{required: true, trigger: "blur", message: "请选择资产"}],
  zcbh: [{required: true, trigger: "blur", message: "请选择资产"}],
  shsl: [{required: true, trigger: "blur", validator: shslValidator}],
  gzyy: [{required: true, trigger: "blur", message: "请说明故障原因"}],
  sxrq: [{required: true, trigger: "blur", message: "请选择送修日期"}],
  isScrapped: [{required: true, trigger: "blur", message: "请选择是否损坏"}],
  wxzk: [{required: true, trigger: "blur", message: "请说明维修状况"}],
  wxfy: [{required: true, trigger: "blur", message: "请填写维修费用"}],
})

/**
 *对话框属性初始化
 */
const props = defineProps(
    {
      id: {
        type: Number,
        default: -1,
        required: true
      },
      dialogTitle: {
        type: String,
        default: "",
        required: true
      },
      dialogVisible: {
        type: Boolean,
        default: false,
        required: true
      }
    }
)

/**
 * 监听属性的变化
 */
watch(
    () => props.dialogVisible,
    (value) => {
      if (value === true) {
        if (props.id !== -1) {
          getAssetFixById(props.id);
          displayBtn.value = 'none';
        }
      }
    }
)

/**
 * 向父组件抛方法
 */
const emits = defineEmits(['update:modelValue', 'initAssetFixList', 'clear'])

/**
 * 手动关闭对话框
 */
const handleClose = () => {
  emits('update:modelValue', false);//关闭dialog
  emits("initAssetFixList");
  emits("clear");
  formDisabled.value = true;
  formRef.value.resetFields();
  kcsl.value = -1;
}

const innerVisible = ref(false)

const getAssetById = async (id) => {
  if (id === -1) {
    ElMessage.error("未选中数据");
  } else {
    ElMessage.success("选择成功");
    formDisabled.value = false; //form禁用取消
    const res = await request.get("/asset/" + id); //根据ID获得资产数据
    //赋值
    form.value.assetid = id;
    form.value.zcmc = res.data.asset.zcmc;
    form.value.zcbh = res.data.asset.zcbh;
    kcsl.value = res.data.asset.kcsl;
  }
}

const getAssetFixById = async (id) => {
  const res = await request.post("assetFix/" + id);
  form.value = res.data.assetFix;
  formDisabled.value = false;
  kcsl.value = res.data.assetFix.asset.kcsl;
}

const handleConfirm = () => {
  if (form.value.assetid === -1) {
    ElMessage.error("请选择数据")
  } else {
    formRef.value.validate((valid) => {
      if (valid) {
        ElMessageBox.confirm(
            "确定填报如下信息吗？",
            "提示",
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
        ).then(async () => {
          const res = await request.post("assetFix/save", form.value)
          if (res.data.code === 200) {
            ElMessage.success(res.data.msg);
            emits("initAssetFixList");
            emits("clear")
            handleClose();
          }
        })
      }
    })
  }
}
</script>

<style scoped></style>